package com.qiantoon.networkdsl.support;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * 通用Preference工具类
 */
public class PreferencesUtil extends BasePreferences {

    private static PreferencesUtil sInstance;

    public static PreferencesUtil getInstance() {
        if (sInstance == null) {
            synchronized (PreferencesUtil.class) {
                if (sInstance == null) {
                    sInstance = new PreferencesUtil();
                }
            }
        }
        return sInstance;
    }

    public static void init(Application application) {
        sApplication = application;
    }

    @Override
    public String getSPFileName() {
        return "common_data";
    }

    @Override
    public void remove(String key) {
        super.remove(key);
        remove(key, getCodeSp());
    }

    @Override
    public void clearAll() {
        super.clearAll();
        clearAll(getCodeSp());
    }

    private static final String CONFIG = "config";
    private static SharedPreferences sp;

    private SharedPreferences getCodeSp() {
        //(存储节点文件名称,读写方式)
        if (sp == null) {
            sp = sApplication.getSharedPreferences(CONFIG, Context.MODE_PRIVATE);
        }
        return sp;
    }

    public void putCodeString(String key, String value) {
        getCodeSp().edit().putString(key, value).commit();
    }

    public String getCodeString(String key, String defValue) {
        return getCodeSp().getString(key, defValue);
    }

    public void putCodeBoolean(String key, boolean value) {
        getCodeSp().edit().putBoolean(key, value).commit();
    }

    public boolean getCodeBoolean(String key) {
        return getCodeSp().getBoolean(key, false);
    }

    public <T> void setUserInfo(T userInfo) {
        if (userInfo == null) {
            remove("UserInfo");
        } else {
            putCodeString("UserInfo", GsonUtils.toJson(userInfo));
        }
    }

    public <T> T getUserInfo(Class<T> tClass) {
        String userInfoStr = getCodeString("UserInfo", "");
        if (TextUtils.isEmpty(userInfoStr)) {
            return null;
        } else {
            return GsonUtils.fromLocalJson(userInfoStr, tClass);
        }
    }


}
